package com.kotlin.hxh.ui.view

import android.content.Context
import androidx.core.content.ContextCompat
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.widget.FrameLayout
import android.widget.ImageView
import com.kotlin.hxh.R

/**
 * @author huxh
 * @date 2018/12/20.
 */
class BottomBarTab : FrameLayout {
    private lateinit var mContext: Context;
    private lateinit var mIcon: ImageView
    private var mTabPostion = -1

    constructor(context: Context, icon: Int) : this(context, null, icon)
    constructor(context: Context, attributeSet: AttributeSet?, icon: Int) : this(context, attributeSet, 0, icon)
    constructor(content: Context, attributeSet: AttributeSet?, defStyleAttr: Int, icon: Int) : super(content, attributeSet, defStyleAttr) {
        init(content, icon)
    }

    private fun init(content: Context, icon: Int) {
        mContext = context
        val typeArray = content.obtainStyledAttributes(intArrayOf(R.attr.selectableItemBackgroundBorderless))
        val drawable = typeArray.getDrawable(0)
        setBackgroundDrawable(drawable)
        typeArray.recycle()
        mIcon = ImageView(context)
        val size = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 27F, resources.displayMetrics).toInt()
        val params = FrameLayout.LayoutParams(size, size)
        params.gravity = Gravity.CENTER
        mIcon.setImageResource(icon)
        mIcon.layoutParams = params
        mIcon.setColorFilter(ContextCompat.getColor(context, R.color.tab_unselect))
        addView(mIcon)
    }

    override fun setSelected(selected: Boolean) {
        super.setSelected(selected)
        if (selected) {
            mIcon.setColorFilter(ContextCompat.getColor(mContext, R.color.colorPrimary))
        } else {
            mIcon.setColorFilter(ContextCompat.getColor(mContext, R.color.tab_unselect))
        }
    }


    fun setTabPosition(position: Int) {
        mTabPostion = position
        if (position == 0) {
            isSelected = true
        }
    }


    fun getTabPosition() = mTabPostion
}
